package com.dnzx.socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class ListeningThread extends Thread {

    private static final Logger LOGGER = LoggerFactory.getLogger(ListeningThread.class);

    private ServerSocket serverSocket;
    private boolean isRunning;
    private static ThreadPoolExecutor executor;
    private static String clientAddress;
    private static Socket socket;

    private static final byte[] GET_EPC = new byte[]{(byte) 0xBB, 0x19, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x06, 0x2E, 0x0D, 0x0A};

    //    public ListeningThread(SocketServer socketServer, ServerSocket serverSocket, int poolsize) {
//        this.socketServer = socketServer;
//        this.serverSocket = serverSocket;
//        this.pool = Executors.newFixedThreadPool(poolsize);
//        isRunning = true;
//    }
    public ListeningThread(ServerSocket serverSocket, int poolsize) {
        this.serverSocket = serverSocket;
        executor = new ThreadPoolExecutor(3, poolsize, 5, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>());
        isRunning = true;
    }

    @Override
    public void run() {
        while (isRunning) {
            if (serverSocket.isClosed()) {
                LOGGER.error("server thread closed:");
                isRunning = false;
            }
            try {
                if (socket == null || socket.isClosed()) {
                    socket = serverSocket.accept();
                } else {
                    Socket socketNext = serverSocket.accept();
                    if (socketNext != null && socketNext.getInetAddress().getHostAddress().equals(clientAddress)) {
                        socket = socketNext;
                    }
                }
                clientAddress = socket.getInetAddress().getHostAddress();
                System.out.println(clientAddress);
                executor.execute(new ConnectionThread(socket));
            } catch (Exception e) {
                LOGGER.error("server thread accept:", e);
//                e.printStackTrace();
            }
        }
    }

    public static void getEpc() throws Exception {
        if (socket == null || socket.isClosed()) {
            throw new Exception("请先连接读写器");
        }
        BufferedInputStream bis = new BufferedInputStream(
                socket.getInputStream());

        DataInputStream dis = new DataInputStream(bis);
//        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
//        DataInputStream dis = new DataInputStream(is);
//        DataOutputStream dos = new DataOutputStream(os);
//        byte[] header = new byte[3];
        try {
            os.write(GET_EPC);
            os.flush();
//            System.out.println("111111");
//
//            is.read(header);
//            String head = ByteUtil.byte2hex(ByteUtil.subByte(header, 0, 1));
//            System.out.println(head);
//
//            String type = ByteUtil.byte2hex(ByteUtil.subByte(header, 1, 1));
//            System.out.println(type);
//            int len = ByteUtil.byte2Int(header, 2, 1);
//            byte[] inputs = new byte[len];
//            is.read(inputs);
//            if (null != type) {
//                switch (type) {
//                    case "96"://查询标签数据响应
//                    case "9A"://写入标签数据响应
//                    default:
//                        break;
//                }
//            }
//
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("", e);

        }


        byte[] bytes = new byte[1]; // 一次读取一个byte
        String ret = "";
        while (dis.read(bytes) != -1) {
            ret += bytesToHexString(bytes) + " ";
            if (dis.available() == 0) { //一个请求
               System.out.println(ret);
            }
            return;
//            if(ret.endsWith("1b 32")){
//                return;
//            }
        }

    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public void stopRunning() {
        isRunning = false;
    }
}
